package fr.lille.inria.adam.lifl.EcoGardeInventory.Services;

import static fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.CommonUtilities.EXTRA_PROXIMITY;
import static fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.CommonUtilities.HANDLE_PROXIMITY_ACTION;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log;

public class ProximityListnerService extends Service implements SensorEventListener{
	private final String TAG = ProximityListnerService.class.getSimpleName();
	private SensorManager mSensorManager;
	private Sensor mProximitySensor;
	@Override
	public void onCreate() {
		super.onCreate();
		
		Log.d(TAG, "onCreat'd");
	}

	@Override
	public void onStart(Intent mIntent, int mStartId) {
		super.onStart(mIntent, mStartId);
		
		startservice();
		
		Log.d(TAG, "onStart'd");
	}
	
	private void startservice() {
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		
		mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
		
		mSensorManager.registerListener(this, mProximitySensor,
				SensorManager.SENSOR_DELAY_NORMAL);

		Log.d(TAG, "ProximityListnerService is start'd!");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		mSensorManager.unregisterListener(this);
		
		Log.d(TAG, "onDestroy'd");
	}
	
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		final float value = event.values[0];
		
		if ( value == 0.0 ) {
			Intent intent = new Intent(HANDLE_PROXIMITY_ACTION);
	       
			intent.putExtra(EXTRA_PROXIMITY, value);
	        
			sendBroadcast(intent);
		}		
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}
